<!-- /admin/admins.php -->
<?php
require_once(__DIR__ . '/../common/auth.php');
check_admin_login();
require_once(__DIR__ . '/../common/db.php');

$msg = '';
$err = '';
$action = $_POST['action'] ?? '';
$id = intval($_POST['id'] ?? 0);

// 新增管理员
if ($action === 'add') {
    $username = trim($_POST['username'] ?? '');
    $name = trim($_POST['name'] ?? '');
    $password = $_POST['password'] ?? '';
    if (!$username || !$password) {
        $err = "用户名和密码不能为空";
    } elseif (strlen($username) < 3) {
        $err = "用户名长度不能低于3位";
    } else {
        $stmt = $db->prepare("SELECT id FROM admin WHERE username=:username");
        $stmt->bindValue(':username', $username, SQLITE3_TEXT);
        $exists = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        if ($exists) {
            $err = "用户名已存在";
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $db->prepare("INSERT INTO admin (username, password, name) VALUES (:username, :password, :name)");
            $stmt->bindValue(':username', $username, SQLITE3_TEXT);
            $stmt->bindValue(':password', $hash, SQLITE3_TEXT);
            $stmt->bindValue(':name', $name, SQLITE3_TEXT);
            $stmt->execute();
            $msg = "管理员添加成功";
        }
    }
}

// 修改密码
if ($action === 'editpwd') {
    $id = intval($_POST['id']);
    $newpwd = $_POST['newpwd'] ?? '';
    if (!$newpwd) {
        $err = "新密码不能为空";
    } else {
        $hash = password_hash($newpwd, PASSWORD_DEFAULT);
        $stmt = $db->prepare("UPDATE admin SET password=:pwd WHERE id=:id");
        $stmt->bindValue(':pwd', $hash, SQLITE3_TEXT);
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        $stmt->execute();
        $msg = "密码修改成功";
    }
}

// 删除管理员（防注入）
if ($action === 'delete') {
    $id = intval($_POST['id']);
    $stmt = $db->prepare("SELECT username FROM admin WHERE id=:id");
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $res = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
    if ($res && $res['username'] != $_SESSION['admin_user']) {
        $stmtDel = $db->prepare("DELETE FROM admin WHERE id=:id");
        $stmtDel->bindValue(':id', $id, SQLITE3_INTEGER);
        $stmtDel->execute();
        $msg = "删除成功";
    } else {
        $err = "不能删除当前登录账号";
    }
}

// 获取所有管理员
$admins = [];
$res = $db->query("SELECT * FROM admin ORDER BY id ASC");
while ($row = $res->fetchArray(SQLITE3_ASSOC)) $admins[] = $row;
?>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>管理员管理 - 工会留言板后台</title>
    <link rel="icon" href="/assets/logo.ico?v=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/assets/style.css?v=<?php echo time(); ?>">
    <style>
    .main.admin-main { max-width: 950px; min-width: 0; margin: 40px auto 0; padding: 36px 40px 28px 40px; }
    .admin-header-bar { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; margin-bottom: 18px; }
    .admin-form-wrap { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin: 0; }
    .admin-form-wrap label { margin: 0 2px 0 0; font-size: 1em; color: #344; white-space: nowrap; }
    .admin-form-wrap input[type="text"], .admin-form-wrap input[type="password"] { border: 1px solid #ccc; border-radius: 6px; padding: 7px 10px; font-size: 1em; width: 130px; box-sizing: border-box; }
    .btn { display: inline-block; padding: 7px 20px; font-size: 1em; border: none; border-radius: 7px; background: #f5f8ff; color: #285bb7; cursor: pointer; box-shadow: 0 1px 2px #e3ebff; transition: background 0.2s, color 0.2s; margin: 0 2px; }
    .btn:hover { background: #d3e2ff; color: #12357a; }
    .btn.danger { background: #ffd8db; color: #ce3237; }
    .btn.danger:hover { background: #ffb5bb; color: #b12a2f; }
    .btn.green { background: #d1f2e6; color: #228868; }
    .btn.green:hover { background: #98e4ce; }
    .btn.blue { background: #cfe6ff; color: #225b99; }
    .btn.blue:hover { background: #b0d8ff; color: #134378; }
    .admin-list { margin-top: 30px; width: 100%; }
    .admin-item { background: #fff; padding: 16px 22px 12px 22px; border-radius: 9px; box-shadow: 0 2px 8px #e5eefd; margin-bottom: 18px; display: flex; align-items: flex-start; gap: 26px; min-width: 0; flex-wrap: wrap; }
    .admin-info { flex: 1; min-width: 0; display: flex; align-items: center; gap: 16px; }
    .admin-username { font-weight: bold; color: #1d388a; font-size: 1.08em; margin-right: 4px; word-break: break-all; }
    .admin-name { color: #666; font-size: 1em; }
    .admin-actions { display: flex; gap: 10px; min-width: 180px; }
    .editpwd-box { display: none; margin-top: 12px; width: 100%; gap: 10px; align-items: center; }
    .admin-item.editing .editpwd-box { display: flex; flex-wrap: wrap; }
    .tip { color: #d94040; font-size: 1.1em; margin-bottom: 15px;}
    .msg-tip { color: #228868; }
    @media (max-width: 1200px) { .main.admin-main { max-width: 98vw; padding: 18px 1vw 16px 1vw; } }
    @media (max-width: 900px) { .admin-form-wrap input[type="text"], .admin-form-wrap input[type="password"] { width: 90px; } .admin-list { width: 100%; } }
    @media (max-width: 700px) {
        .main.admin-main { padding: 8px 1vw 8px 1vw; }
        .admin-form-wrap { flex-direction: column; gap: 6px;}
        .admin-item { flex-direction: column; gap: 12px; padding: 13px 8px 8px 10px;}
        .admin-info, .admin-actions { flex-direction: row; gap: 8px;}
        .editpwd-box { flex-direction: column; gap: 8px;}
    }
    </style>
    <script>
    function showEditPwd(id) {
        document.querySelectorAll('.admin-item').forEach(function(item){
            item.classList.remove('editing');
        });
        document.getElementById('admin'+id).classList.add('editing');
        setTimeout(function(){
            var input = document.querySelector('#admin'+id+' input[name="newpwd"]');
            if(input) input.focus();
        },100);
    }
    function hideEditPwd(id) {
        document.getElementById('admin'+id).classList.remove('editing');
    }
    </script>
</head>
<body>
<?php include('../components/header.php'); ?>
<div style="display:flex;">
    <?php include('../components/menu.php'); ?>
    <div class="main admin-main">
        <div class="admin-header-bar">
            <h2 class="msg-title" style="margin-bottom:0;">管理员账号管理</h2>
        </div>
        <?php
        if($err) echo "<div class='tip'>".htmlspecialchars($err)."</div>";
        if($msg) echo "<div class='msg-tip'>".htmlspecialchars($msg)."</div>";
        ?>
        <!-- 新增管理员 -->
        <form method="post" class="admin-form-wrap" autocomplete="off" style="margin:18px 0 24px 0;">
            <input type="hidden" name="action" value="add">
            <label>账号</label>
            <input type="text" name="username" maxlength="20" required autocomplete="off">
            <label>姓名</label>
            <input type="text" name="name" maxlength="20" autocomplete="off">
            <label>密码</label>
            <input type="password" name="password" maxlength="32" required autocomplete="new-password">
            <button type="submit" class="btn green">添加管理员</button>
        </form>
        <!-- 管理员列表 -->
        <div class="admin-list">
        <?php foreach($admins as $ad): ?>
            <div class="admin-item" id="admin<?php echo $ad['id']; ?>">
                <div class="admin-info">
                    <span class="admin-username"><?php echo htmlspecialchars($ad['username']); ?></span>
                    <span class="admin-name"><?php echo htmlspecialchars($ad['name']); ?></span>
                </div>
                <div class="admin-actions">
                    <button type="button" class="btn blue" onclick="showEditPwd(<?php echo $ad['id']; ?>)">修改密码</button>
                    <?php if ($ad['username'] !== $_SESSION['admin_user']): ?>
                    <form method="post" style="display:inline;">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?php echo $ad['id']; ?>">
                        <button type="submit" class="btn danger" onclick="return confirm('确定删除该管理员？')">删除</button>
                    </form>
                    <?php endif; ?>
                </div>
                <!-- 修改密码区域 -->
                <form method="post" class="admin-form-wrap editpwd-box">
                    <input type="hidden" name="action" value="editpwd">
                    <input type="hidden" name="id" value="<?php echo $ad['id']; ?>">
                    <label>新密码</label>
                    <input type="password" name="newpwd" maxlength="32" required autocomplete="new-password">
                    <button type="submit" class="btn green">确认修改</button>
                    <button type="button" class="btn" onclick="hideEditPwd(<?php echo $ad['id']; ?>)">取消</button>
                </form>
            </div>
        <?php endforeach; ?>
        </div>
    </div>
</div>
</body>
</html>
